#!/bin/bash

#set -x
#[ "${FLOCKER}" != "$0" ] && { echo "$$ try lock"; exec env FLOCKER="$0" flock -en "$0" "$0" "$@"; } || { echo "$$ get lock"; }
#sleep 10 &

MAX=4
INDEX=-1
THREADS=()
while true; do
      {   flock -n 9 || { echo " $$ failed to get lock"; sleep 1; }
         if [ $INDEX -eq $MAX ]; then
             flock -u 9
             echo "$$ waiting ...."
             wait $(for x in ${THREADS[@]};do echo -n "$x ";done)
             THREADS=()
             INDEX=-1
             continue
         fi 
         ((INDEX++))
         echo "$$ commands executed under lock ... $INDEX"
         sleep 1
         echo "$$ commands executed, then release lock ..."
#         /bin/bash -c "echo \"\$\$ start...\" && flock -n 9 && sleep 5 && flock -u 9 && echo \"concurrent task start \" && sleep 30" &
         /bin/bash -c "echo \"\$\$ start...\" && sleep 5 " &
         THREADS[$INDEX]=$!
         flock -u 9
    } 9>/var/lock/mylockfile
done


